﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using KnowledgeCommunity.Model;
using KnowledgeCommunity.Service;
using KnowledgeCommunity.Web.Models;
using KnowledgeCommunity.Web.DbHelper;

namespace KnowledgeCommunity.Web.Controllers
{
    public class TopicController : Controller
    {
        TopicHelper myTopicHelper = new TopicHelper();
        //
        // GET: /Notice/

        public ActionResult Index()
        {
            var model = myTopicHelper.FindByBelongTo(1);
            ViewData["TopicList"] = model;
            return View();
        }

        public ActionResult QuestionAndAnswer()
        {
            var model = myTopicHelper.FindByBelongTo(4);
            ViewData["TopicList"] = model;
            return View();
        }

        public ActionResult Cooperating()
        {
            var model = myTopicHelper.FindByBelongTo(5);
            ViewData["TopicList"] = model;
            return View();
        }

        public ActionResult UseTerms()
        {
            var model = myTopicHelper.FindByBelongTo(6);
            ViewData["TopicList"] = model;
            return View();
        }

        public ActionResult UserGuide()
        {
            var model = myTopicHelper.FindByBelongTo(7);
            ViewData["TopicList"] = model;
            return View();
        }

        [Authorize(Roles = "admin,editor")]
        public ActionResult List()
        {
            KnowledgeCommunity.Web.Models.Page Model = new Page();
            Model.CurrentPageIndex = 1;  //当前页 默认第一页

            int SkinCount = (Model.CurrentPageIndex - 1) * Model.PageSize;

            //测试用例。实际用自己的逻辑获取数据
            List<Topic> datesource = GetDataSource();//要分页的数据源
            Model.TopicsList = datesource.Where(r => r.Id >= 0).Skip(SkinCount).Take(Model.PageSize).ToList();
            //测试用例。实际用自己的逻辑获取数据

            //是否开启Ajax分页
            Model.IsAjax = true;
            Model.TotalCount = datesource.Count;//获取记录总数

            //获取分页数据
            Model.TopicsList = datesource.Where(r => r.Id >= 0).Skip(SkinCount).Take(Model.PageSize).ToList();
            return View(Model);

        }

        private List<Topic> GetDataSource()
        {
            var Topic = myTopicHelper.FindAll();
            List<Topic> model = new List<Topic>();
            foreach (var item in Topic)
            {
                model.Add(item);
            }
            return model;
        }

        [Authorize(Roles = "admin,editor")]
        public ActionResult PageIndex(Models.Page Model)
        {

            //分页数据源。自己写逻辑获取。

            int SkinCount = (Model.CurrentPageIndex - 1) * Model.PageSize;

            //测试用例。实际用自己的逻辑获取数据
            List<Topic> datesource = GetDataSource();//要分页的数据源
            Model.TopicsList = datesource.Where(r => r.Id >= 0).Skip(SkinCount).Take(Model.PageSize).ToList();
            //测试用例。实际用自己的逻辑获取数据

            Model.TotalCount = datesource.Count;//获取记录总数
            if (Request.IsAjaxRequest())  //是AJAX请求的话返回AJAX分页数据
            {
                Model.IsAjax = true;
                return View(Model);
            }
            else
            {
                Model.IsAjax = false;
                return this.PartialView("List", Model);
            }
            //return View(Model);
        }

        [Authorize]
        [HttpPost]
        public ActionResult Search()
        {
            string title = Request.Form["s_title"];
            string cont = Request.Form["s_cont"];
            DateTime start, end;
            start = Convert.ToDateTime("2012-1-1");
            end = Convert.ToDateTime("2100-12-31");
            if (Request.Form["s_time"].ToString() != "")
            {
                start = Convert.ToDateTime(Request.Form["s_time"]);
            }
            if (Request.Form["e_time"].ToString() != "")
            {
                end = Convert.ToDateTime(Request.Form["e_time"]);
            }
            var Topics = myTopicHelper.SearchByKeyAndTime(title, cont, start, end);
            return View(Topics);

        }

        public ActionResult Details(int id)
        {
            //更新关注次数
            var model = myTopicHelper.FindById(id);
            int i = model.ClickNum;
            i++;
            model.ClickNum = i;
            DoUpdateModel(model);
            return View(model);
            //ViewData["TopicDetails"] = model;
            //return View();
        }

        [Authorize(Roles = "admin,editor")]
        public ActionResult Create()
        {
            return View();
        }

        [ValidateInput(false)]
        [Authorize(Roles = "admin,editor")]
        [HttpPost]
        public ActionResult Create(Topic model)
        {
            model.AddTime = DateTime.Now;
            model.EditUser = HttpContext.User.Identity.Name;
            model.ClickNum = 1;
            model.BelongTo =Convert.ToInt32(Request.Form["NewsBelong"].ToString());
            model.ShapeCode = "M" + RandomNumber.GenerateRandomNumber();

            bool n = myTopicHelper.Create(model);
            if (n)
                return RedirectToAction("List", "Topic");
            else
                return RedirectToAction("Error", "Notice", new { type = 1 });
        }

        [Authorize(Roles = "admin,editor")]
        public ActionResult Edit(int id)
        {
            var Topics = myTopicHelper.FindById(id);
            return View(Topics);
        }

        [ValidateInput(false)]
        [Authorize(Roles = "admin,editor")]
        [HttpPost]
        public ActionResult Edit(Topic model)
        {
            DoUpdateModel(model);
            return RedirectToAction("Details", new { id = model.Id });
        }

        [Authorize(Roles = "admin,editor")]
        public ActionResult Delete(int id)
        {
            var Topics = myTopicHelper.FindById(id);
            return View(Topics);
        }

        [Authorize(Roles = "admin,editor")]
        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            bool n = myTopicHelper.Delete(id);
            if (n)
                return RedirectToAction("List", "Topic");
            else
                return RedirectToAction("Error", "Notice", new { type = 2 });
        }


        CKCDB mydb = new CKCDB();

        private void DoUpdateModel(Topic model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    var app = mydb.Topics.Find(model.Id);
                    UpdateModel(app);
                    mydb.SaveChanges();
                }
                catch (Exception ex)
                {
                    string message = "Create in table<Topics>" + ex.ToString();
                    WriteLog.WriteSysLog(message);
                }
            }
        }

    }
}
